import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_router.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/magma_report_dialog.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';

/// 他人页面视图模型
class OtherUserProfileViewModel extends BaseViewModel {
  final String targetUserId;

  OtherUserProfileViewModel(this.targetUserId) {
    // 监听 contentBroadcaster 的变化（用于实时更新点赞数）
    appState.contentBroadcaster.addListener(_onContentChanged);
    // 监听 followManager 的变化（用于实时更新粉丝/关注数）
    appState.followManager.addListener(_onFollowChanged);
  }

  void _onContentChanged() {
    notifyListeners();
  }

  void _onFollowChanged() {
    notifyListeners();
  }

  @override
  void dispose() {
    appState.contentBroadcaster.removeListener(_onContentChanged);
    appState.followManager.removeListener(_onFollowChanged);
    super.dispose();
  }

  /// 获取目标用户
  UserModel? get targetUser => appState.userStore.getUserById(targetUserId);

  /// 获取用户发布的动态列表
  List<ContentModel> get userDynamics {
    if (targetUser == null) return [];
    return appState.contentBroadcaster.fetchUserContent(targetUser!.id);
  }

  /// 获取用户统计数据
  Map<String, int> get userStats {
    if (targetUser == null) {
      return {'fan': 0, 'follow': 0, 'like': 0};
    }

    return {
      'fan': appState.followManager.getFollowersCount(targetUser!.id),
      'follow': appState.followManager.getFollowingCount(targetUser!.id),
      'like': appState.contentBroadcaster.getUserTotalLikes(targetUser!.id),
    };
  }

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 检查是否已关注目标用户
  bool get isFollowing {
    if (!isLoggedIn || currentUser == null || targetUser == null) return false;
    return appState.followManager.isFollowing(currentUser!.id, targetUser!.id);
  }

  /// 切换关注状态
  Future<bool> toggleFollow() async {
    if (!isLoggedIn || currentUser == null || targetUser == null) return false;

    if (isFollowing) {
      // 如果已关注，则取消关注
      return await appState.followManager.terminateFollow(
        followerId: currentUser!.id,
        followingId: targetUser!.id,
      );
    } else {
      // 如果未关注，则关注
      return await appState.followManager.establishFollow(
        followerId: currentUser!.id,
        followingId: targetUser!.id,
      );
    }
  }

  /// 导航到单聊页面
  void navigateToChat() {
    if (!isLoggedIn || targetUser == null) return;

    // 检查是否已有对话，如果没有则创建
    final conversationExists = appState.chatCoordinator
        .fetchChatList(currentUser!.id)
        .any((chat) => chat['userId'] == targetUser!.id);

    if (!conversationExists) {
      // 创建一个新的对话（通过发送一条欢迎消息）
      // 这里可以选择性地发送一条消息，或者直接跳转
    }

    // 导航到单聊页面
    QR.to(MagmaRouter.singleChatPath.replaceAll(':userId', targetUser!.id));
  }
}

/// 他人页面
class OtherUserStory extends StatefulWidget {
  final String userId;

  const OtherUserStory({super.key, required this.userId});

  @override
  State<OtherUserStory> createState() => _OtherUserStoryState();
}

class _OtherUserStoryState extends State<OtherUserStory> {
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<OtherUserProfileViewModel>.reactive(
      viewModelBuilder: () => OtherUserProfileViewModel(widget.userId),
      disposeViewModel: false,
      initialiseSpecialViewModelsOnce: true,
      builder: (context, viewModel, child) {
        // 检查用户是否存在
        if (viewModel.targetUser == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(MagmaConstant.background),
                  fit: BoxFit.cover,
                ),
              ),
              child: SafeArea(
                child: Column(
                  children: [
                    _buildTitleBar(context, viewModel),
                    Expanded(
                      child: Center(
                        child: Text('User not found').inter(
                          fontSize: 16.sp,
                          color: MagmaColor.white,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }

        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // 标题栏
                  _buildTitleBar(context, viewModel),

                  // 可滚动内容区域
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          // 用户信息区域
                          _buildUserProfileSection(viewModel),

                          SizedBox(height: 8.h),

                          // 分隔线
                          _buildSeparator(),

                          SizedBox(height: 8.h),

                          // 动态列表
                          _buildDynamicsList(viewModel),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildTitleBar(
    BuildContext context,
    OtherUserProfileViewModel viewModel,
  ) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          MagmaTap(
            onTap: () => QR.back(),
            child: Image.asset(
              MagmaConstant.back,
              width: 20.w,
              height: 20.w,
              color: MagmaColor.white,
            ),
          ),

          // 标题
          Expanded(
            child: Center(
              child: Text('PERSONAL').blackHanSans(
                fontSize: 24.sp,
                color: MagmaColor.white,
                fontWeight: FontWeight.w400,
              ),
            ),
          ),

          // 举报按钮
          MagmaTap(
            onTap: () => _showReportDialog(context, viewModel),
            child: Image.asset(
              MagmaConstant.report,
              width: 24.w,
              height: 24.w,
              color: MagmaColor.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 显示举报用户对话框
  void _showReportDialog(
    BuildContext context,
    OtherUserProfileViewModel viewModel,
  ) {
    MagmaReportDialog.showReportDialog(
      context,
      title: 'Report User',
      subtitle: 'Please select a reason for reporting this user',
      onReportSubmitted: (option) {
        // 关闭对话框
        Navigator.of(context).pop();
        // 显示成功提示
        MagmaToast.success(context, title: 'User reported successfully');
        // 返回上一个页面
        QR.back();
      },
    );
  }

  /// 构建用户信息区域
  Widget _buildUserProfileSection(OtherUserProfileViewModel viewModel) {
    final user = viewModel.targetUser!;
    final stats = viewModel.userStats;

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children: [
          SizedBox(height: 16.h),

          // 用户头像
          CircleAvatar(radius: 50.r, backgroundImage: AssetImage(user.avatar)),

          SizedBox(height: 16.h),

          // 用户名
          Text(user.username).blackHanSans(
            fontSize: 20.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w700,
          ),

          SizedBox(height: 12.h),

          // 用户简介
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 8.w),
            child: Text(
              'Life Is Not About Waiting For The Storm To Pass, It\'s About Learning To Dance In The Rain.',
              textAlign: TextAlign.center,
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ).inter(
              fontSize: 14.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w400,
            ),
          ),

          SizedBox(height: 24.h),

          // 统计数据
          _buildStatsRow(stats),

          SizedBox(height: 24.h),

          // 关注和聊天按钮
          _buildActionButtons(viewModel),

          SizedBox(height: 16.h),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons(OtherUserProfileViewModel viewModel) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 40.w),
      child: Row(
        children: [
          // 关注按钮
          Expanded(
            child: MagmaTap(
              onTap: () => _handleFollowTap(viewModel),
              child: Container(
                height: 48.h,
                decoration: BoxDecoration(
                  color:
                      viewModel.isFollowing
                          ? MagmaColor.grey.withOpacity(0.3)
                          : MagmaColor.purple,
                  borderRadius: BorderRadius.circular(24.r),
                  border: Border.all(
                    color:
                        viewModel.isFollowing
                            ? MagmaColor.white.withOpacity(0.5)
                            : MagmaColor.purple,
                    width: 1.w,
                  ),
                ),
                child: Center(
                  child: Text(
                    viewModel.isFollowing ? '- Unfollow' : '+ Follow',
                  ).blackHanSans(
                    fontSize: 16.sp,
                    color: MagmaColor.white,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ),

          SizedBox(width: 16.w),

          // 聊天按钮
          Expanded(
            child: MagmaTap(
              onTap: () => _handleChatTap(viewModel),
              child: Container(
                height: 48.h,
                decoration: BoxDecoration(
                  color: MagmaColor.black,
                  borderRadius: BorderRadius.circular(24.r),
                  border: Border.all(color: MagmaColor.white, width: 1.w),
                ),
                child: Center(
                  child: Text('Chat').blackHanSans(
                    fontSize: 16.sp,
                    color: MagmaColor.white,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 处理关注按钮点击
  Future<void> _handleFollowTap(OtherUserProfileViewModel viewModel) async {
    // 检查是否登录
    if (!viewModel.isLoggedIn) {
      await LoginRequiredDialog.show(context);
      return;
    }

    // 保存当前关注状态
    final wasFollowing = viewModel.isFollowing;

    // 切换关注状态
    final result = await viewModel.toggleFollow();
    if (result) {
      MagmaToast.success(
        context,
        title: wasFollowing ? 'Unfollowed' : 'Followed',
      );
    } else {
      MagmaToast.error(context, title: 'Operation failed');
    }
  }

  /// 处理聊天按钮点击
  void _handleChatTap(OtherUserProfileViewModel viewModel) {
    // 检查是否登录
    if (!viewModel.isLoggedIn) {
      LoginRequiredDialog.show(context);
      return;
    }

    // 导航到聊天页面
    viewModel.navigateToChat();
  }

  /// 构建统计数据行
  Widget _buildStatsRow(Map<String, int> stats) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildStatItem('Fan', stats['fan']!.toString()),
        _buildStatDivider(),
        _buildStatItem('Follow', stats['follow']!.toString()),
        _buildStatDivider(),
        _buildStatItem('Like', stats['like']!.toString()),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(value).blackHanSans(
          fontSize: 18.sp,
          color: MagmaColor.white,
          fontWeight: FontWeight.w700,
        ),
        SizedBox(height: 4.h),
        Text(label).inter(
          fontSize: 12.sp,
          color: MagmaColor.white,
          fontWeight: FontWeight.w400,
        ),
      ],
    );
  }

  /// 构建统计分隔线
  Widget _buildStatDivider() {
    return Container(
      width: 1.w,
      height: 40.h,
      color: MagmaColor.white.withOpacity(0.3),
    );
  }

  /// 构建分隔线
  Widget _buildSeparator() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 0.h),
      child: Image.asset(
        MagmaConstant.decoration,
        width: double.infinity,
        height: 20.h,
        fit: BoxFit.fitWidth,
      ),
    );
  }

  /// 构建动态列表
  Widget _buildDynamicsList(OtherUserProfileViewModel viewModel) {
    final dynamics = viewModel.userDynamics;

    if (dynamics.isEmpty) {
      return Center(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 40.h),
          child: Text(
            'No posts yet',
          ).inter(fontSize: 16.sp, color: MagmaColor.white.withOpacity(0.6)),
        ),
      );
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        children:
            dynamics.map((dynamic) {
              return _buildDynamicItem(dynamic, viewModel);
            }).toList(),
      ),
    );
  }

  /// 构建动态项
  Widget _buildDynamicItem(
    ContentModel dynamic,
    OtherUserProfileViewModel viewModel,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: MagmaTap(
        onTap: () {
          QR.to(
            MagmaRouter.dynamicDetailPath.replaceAll(':dynamicId', dynamic.id),
          );
        },
        child: Container(
          decoration: BoxDecoration(
            color: MagmaColor.black,
            borderRadius: BorderRadius.circular(6.r),
            border: Border.all(color: MagmaColor.white, width: 1.w),
          ),
          child: Padding(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 发布日期和举报按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Release Date: ${_formatDate(dynamic.createdAt)}',
                    ).blackHanSans(
                      fontSize: 14.sp,
                      color: MagmaColor.white,
                      fontWeight: FontWeight.w400,
                    ),
                    // MagmaTap(
                    //   onTap: () => _showDynamicReportDialog(dynamic, viewModel),
                    //   child: Image.asset(
                    //     MagmaConstant.report,
                    //     width: 20.w,
                    //     height: 20.w,
                    //     color: MagmaColor.white,
                    //   ),
                    // ),
                  ],
                ),

                SizedBox(height: 12.h),

                // 动态图片
                AspectRatio(
                  aspectRatio: 346 / 232,
                  child: Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2.r),
                      image: DecorationImage(
                        image: AssetImage(
                          dynamic.imagePath ??
                              dynamic.coverImagePath ??
                              MagmaConstant.dynamic1,
                        ),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child:
                        dynamic.type == ContentType.video
                            ? Center(
                              child: Icon(
                                Icons.play_arrow,
                                color: Colors.white,
                                size: 48.w,
                              ),
                            )
                            : null,
                  ),
                ),

                SizedBox(height: 12.h),

                // 动态详情文字（两行）
                Text(
                  dynamic.content,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ).inter(
                  fontSize: 16.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w400,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    const months = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
    ];
    return '${months[date.month - 1]} ${date.day}, ${date.year}';
  }
}
